<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="realname">
        <el-input
          v-model="queryParams.realname"
          placeholder="姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="邮箱"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item prop="organizationCode">
        <el-input
          v-model="queryParams.organizationCode"
          placeholder="单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item prop="identity">
        <el-select v-model="queryParams.identity" placeholder="身份" clearable>
          <el-option
            v-for="(item, index) in identitys"
            :key="index"
            :label="item.identityName"
            clearable
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item prop="isRegimental">
        <el-select
          v-model="queryParams.isRegimental"
          placeholder="会员类别"
          clearable
        >
          <el-option
            v-for="(item, index) in roles"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="arrears">
        <el-select
          v-model="queryParams.arrears"
          placeholder="欠款状态"
          clearable
        >
          <el-option
            v-for="(item, index) in arrearsOptions"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <div class="number-picker">
          <el-input
            type="number"
            min="0"
            v-model="queryParams.minAcademicCurrency"
            placeholder="最低学术币, 请输入数字"
            clearable
          ></el-input>
          <span style="margin: 0 10px">&gt;</span>
          <el-input
            type="number"
            min="0"
            v-model="queryParams.maxAcademicCurrency"
            placeholder="最高学术币，请输入数字"
            clearable
          ></el-input>
        </div>
      </el-form-item>

      <el-form-item prop="time">
        <el-date-picker
          v-model="queryParams.time"
          value-format="timestamp"
          type="datetimerange"
          range-separator=">"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['userManager:user:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="userList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户ID" align="center" prop="id" />
      <el-table-column label="真实姓名" align="center" prop="realname" />
      <el-table-column label="微信号" align="center" prop="wxCode">
        <template slot-scope="scope">
          {{ scope.row.wxCode ? scope.row.wxCode : "无" }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="头像" align="center" prop="avatar" /> -->
      <el-table-column label="手机号" align="center" prop="mobile" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="单位" align="center" prop="organizationCode" />
      <el-table-column label="身份" align="center">
        <template slot-scope="scope">
          <span>{{ computedSf(scope.row.identity) }} </span>
        </template>
      </el-table-column>
      <el-table-column
        label="推荐人ID"
        align="center"
        prop="recommendedUserId"
      />
      <el-table-column label="会员类别" align="center">
        <template slot-scope="scope" v-if="roles">
          {{
            scope.row.teamId != null && scope.row.teamId != 0
              ? "签约会员"
              : "普通会员"
          }}
        </template>
      </el-table-column>
      <el-table-column label="所属团队" align="center" prop="teamName" />

      <el-table-column label="个人折扣" align="center" prop="discount">
        <template slot-scope="scope">{{ (scope.row.discount && scope.row.discount !==100) ? (scope.row.discount / 10 + '折') : "无"}}</template>
      </el-table-column>

      <el-table-column
        label="剩余学术币"
        align="center"
        prop="academicCurrency"
      />

      <el-table-column
        label="累计使用学术币"
        align="center"
        prop="useOfAcademicCoins"
      />

      <el-table-column
        label="查重券"
        align="center"
        prop="duplicateCheckCoupon"
      />

      <!-- 欠款状态TODO -->
      <el-table-column label="欠款状态" align="center" prop="arrears">
        <template slot-scope="scope">{{ arrears[scope.row.arrears] }}</template>
      </el-table-column>

      <!-- <el-table-column label="简介" align="center" prop="description" /> -->

      <el-table-column label="注册时间" align="center" prop="createTime" />

      <el-table-column label="最后登录" align="center" prop="lastLoginTime" />

      <el-table-column label="登录次数" align="center" prop="loginNum" />

      <el-table-column label="科藤备注" align="center" prop="remark" />

      <el-table-column
        label="操作"
        fixed="right"
        align="center"
        class-name="small-padding fixed-width"
        width="280"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row, 'duplicateVisiable')"
            v-hasPermi="['userManager:user:edit']"
            >查看详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="updateOperation(scope.row, 'duplicateVisiable')"
            v-hasPermi="['userManager:user:duplicateCheckCoupon']"
            >设置查重券</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="!scope.row.recommendedUserId"
            @click="updateOperation(scope.row, 'recommendVisiable')"
            v-hasPermi="['userManager:user:recommend']"
            >推荐人ID</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="updateOperation(scope.row, 'discountVisiable')"
            v-hasPermi="['userManager:user:discount']"
            >设置折扣</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 设置查重券  -->
    <conpon
      :visiable="duplicateVisiable"
      title="设置查重券"
      :row="row"
      :requestURL="duplicateURL"
      column="duplicateCheckCoupon"
      @updateData="updateConpon"
      @close="closeConpon"
    ></conpon>
    <!-- 设置推荐人  -->
    <conpon
      :visiable="recommendVisiable"
      title="设置推荐人"
      :row="row"
      :requestURL="updateRecommendURL"
      column="recommendedUserId"
      @updateData="updateRecommendData"
      @close="closeRecommend"
    >
    </conpon>

    <!-- 设置折扣  -->
    <zk-dialog
      :visible="discountVisiable"
      title="设置折扣"
      onceLabel="用户ID"
      :id="row.id"
      :onceContent="row.id"
      :twiceContent="
        row.discount && row.discount !== 100 ? row.discount / 10 : null
      "
      oncePlaceholder="获取用户ID失败"
      :onceDisabled="true"
      twiceLabel="设置折扣"
      twicePlaceholder="请设置折扣"
      twiceType="number"
      @cancel="closeDiscount"
      @confirm="updateDiscountData"
    >
    </zk-dialog>
  </div>
</template>
<script>
import { listUser, delUser, addUser, updateUser } from "@/api/user";
import { listIdentitys } from "../../api/configManager/identity";
import { ARRERS } from "../../constant/const";
import { timestampToDate } from "../../utils/time";
import { Message } from "element-ui";
import RequestRemote from "@/utils/request";
const roles = [
  {
    name: "普通会员",
    id: 0,
  },
  {
    name: "签约会员",
    id: 1,
  },
];
const arrearsOptions = [
  {
    name: "是",
    id: 1,
  },
  {
    name: "否",
    id: 0,
  },
];

export default {
  name: "User",
  data() {
    return {
      //是否欠款
      arrearsOptions,
      // 会员类型
      roles,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户管理表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //  查重券 弹框
      duplicateVisiable: false,

      recommendVisiable: false,

      // 折扣
      discountVisiable: false,
      // 当前点击行的id
      row: {},

      duplicateURL: "/userManager/user/duplicateCheckCoupon",

      updateRecommendURL: "/userManager/user/updateRecommend",

      updateDiscountURL: "/userManager/user/configDiscount",

      identitys: [],
      identityMap: {},
      arrears: ARRERS,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        wxCode: null,
        password: null,
        salt: null,
        avatar: null,
        realname: null,
        mobile: null,
        email: null,
        sex: null,
        description: null,
        organizationCode: null,
        age: null,
        teamId: null,
        birthday: null,
        identity: null,
        status: null,
        lastLoginTime: null,
        recommendedUserId: null,
        lastLoginIp: null,
        isRegimental: null,
        arrears: null,
        minAcademicCurrency: undefined,
        maxAcademicCurrency: undefined,
        time: undefined
      },
      isSearch: false,
    };
  },
  created() {
    listIdentitys(this);
  },
  mounted() {
    this.getList();
  },

  components: {
    conpon: () => import("./component/conpon.vue"),
    "zk-dialog": () => import("@/components/zkDialog/index.vue"),
  },

  methods: {
    updateConpon(item, column, value) {
      item[column] = parseInt(value);
    },

    updateRecommendData(item, column, value) {
      item[column] = value;
    },

    updateDiscountData(id, discount) {
      RequestRemote.post(this.updateDiscountURL, {
        id,
        discount: discount ? discount * 10 : 100
      }).then((res) => {
        this.$message.success("操作成功");
        this.row['discount'] = discount ? discount * 10  : null;
        this.closeDiscount()
      });
    },

    /** 查询用户管理列表 */
    getList() {
      this.loading = true;
      let params = {};
      if (this.isSearch) {
        console.log(" this.queryParams.time", this.queryParams.time);
        params = Object.assign(
          {},
          {
            ...this.queryParams,
            startTime: this.queryParams.time && this.queryParams.time[0]
              ? this.queryParams.time[0] / 1000
              : "",
            endTime: this.queryParams.time && this.queryParams.time[1]
              ? this.queryParams.time[1] / 1000
              : "",
          }
        );
      } else {
        params = {
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize,
        };
      }
      listUser(params).then((response) => {
        this.userList = response.rows;

        this.userList.forEach((ele) => {
          ele.lastLoginTime = timestampToDate(ele.lastLoginTime);

          ele.createTime = timestampToDate(ele.createTime);
        });

        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userName: null,
        wxCode: null,
        password: null,
        salt: null,
        avatar: null,
        realname: null,
        mobile: null,
        email: null,
        sex: null,
        description: null,
        organizationCode: null,
        age: null,
        teamId: null,
        birthday: null,
        identity: null,
        status: null,
        lastLoginTime: null,
        recommendedUserId: null,
        lastLoginIp: null,
        createTime: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.isSearch = true;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.maxAcademicCurrency = null;
      this.queryParams.minAcademicCurrency = null;

      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /**
     * 更新操作
     * @param {{}} item
     * @param {String} key
     */
    updateOperation(item, key) {
      this.row = item;
      console.log("this.clickId", this.clickId);
      this[key] = true;
    },

    closeConpon(visiable) {
      this.duplicateVisiable = visiable;
    },

    closeRecommend(visiable) {
      this.recommendVisiable = visiable;
    },
    closeDiscount() {
      this.discountVisiable = false;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;

      localStorage.setItem("selectItem", JSON.stringify(row));

      this.$router.push({
        path: `/user/edit/${row.id}`,
      });

      // getUser(id).then((response) => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改用户管理";
      // });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateUser(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除用户管理编号为"' + ids + '"的数据项？')
        .then(function () {
          return delUser(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      console.log(this.ids);
      this.download(
        "userManager/user/export",
        {
          ...this.queryParams,
          ids: this.ids.length ? this.ids : undefined,
        },
        `user_${new Date().getTime()}.xlsx`
      );
    },
  },

  computed: {
    computedSf() {
      return (e) => {
        let name = "";
        let obj = this.identitys && this.identitys.find((ite) => ite.id == e);
        if (obj) {
          name = obj.identityName;
        }
        return name;
      };
    },
  },
};
</script>

<style scoped>
.number-picker {
  display: flex;
  align-items: center;
}
</style>
